//
//  ABRefreshControl.swift
//  microblog
//
//  Created by 安波 on 15/11/3.
//  Copyright © 2015年 anbo. All rights reserved.
//

import UIKit
import FFAutoLayout

class ABRefreshControl: UIRefreshControl {
    
    // MARK: - 属性
    /// 箭头旋转的值
    private let refreshControlOffset: CGFloat = -60
    
    /// 标记，用于除去反复打印
    private var isUP = false
    
    /// 覆盖父类的frame
    override var frame: CGRect {
        didSet{
            
            if frame.origin.y >= 0 {
                return
            }
            // 判断系统的刷新控件是否在刷新
            if refreshing {
                // 在刷新，开始旋转
                startLoading()
            }
            
            if frame.origin.y < refreshControlOffset && !isUP { // 60以上
//                print("箭头转上去")
                isUP = true
                rotationTipViewIcon(isUP)
            }else if frame.origin.y > refreshControlOffset && isUP { // 0-60之间
//                print("箭头转下去")
                isUP = false
                rotationTipViewIcon(isUP)
            }
            
        }
    }
    // 重写 endRefreshing
    override func endRefreshing() {
        super.endRefreshing()
        stopLoading()
    }
    // MARK: - 构造函数
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init() {
        super.init()
        
        tintColor = UIColor.clearColor()
        // 准备UI
        prepareUI()
    }
    
    // MARK: - 准备UI
    private func prepareUI(){
        
        addSubview(loadView)
        addSubview(pullDownView)
        
        // 添加约束  注意：在这约束的时候，需要设置size，否则位置约束会出错
        pullDownView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 160, height: 60))
        loadView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 160, height: 60))
    }

    // MARK: - 懒加载
    /// 自定正在加载的  View
    private lazy var loadView: ABLoadView = ABLoadView()
    /// 自定义下拉刷新  View
    private lazy var pullDownView: ABPullDownRefreshView = ABPullDownRefreshView()
    
    
    // MARK: - 旋转动画
    // TODO: 纯代码创建时，动画效果实现
    /**
        箭头旋转动画
    - parameter isUp: true,表示朝上, false,朝下
    */
    func rotationTipViewIcon(isUp: Bool) {
        UIView.animateWithDuration(0.25) { () -> Void in
            // 判断 如果箭头是朝上，顺时针旋转；如果箭头是朝下，逆时针旋转到初始状态
            self.pullDownView.imageView.transform = isUp ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) : CGAffineTransformIdentity
        }
    }
    
    // 开始旋转
    func startLoading(){
        // 如果动画正在执行，不添加动画
        let animKey = "animKey"
        
        // 获取图层上所有正在执行的动画的key
        if let _ = loadView.layer.animationForKey(animKey){
            // 找到对应的动画，动画正在执行，直接返回
            return
        }
        // 隐藏下拉   注意：程序执行是从上往下执行，所以需要注意顺序
        pullDownView.hidden = true
    
        // 旋转
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = M_PI * 2
        anim.duration = 0.25
        anim.repeatCount = MAXFLOAT
        
        anim.removedOnCompletion = false
        
        // 开始旋转  加载数据
        loadView.imageView.layer.addAnimation(anim, forKey: animKey)
    }
    
    // 停止旋转
    func stopLoading(){
        
        // 移除动画
        loadView.imageView.layer.removeAllAnimations()
        
        // 显示下拉
        pullDownView.hidden = false
    }
    
}

// MARK: -
// TODO: 正在加载的  View
class ABLoadView: UIView {
    // MARK: - 构造方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.whiteColor()
        
        prepareUI()
    }

    /// 准备UI
    private func prepareUI(){
        // 添加子控件
        addSubview(imageView)
        addSubview(label)
        
        // 添加约束
        imageView.ff_AlignInner(ff_AlignType.CenterLeft, referView: self, size: nil)
        label.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: imageView, size: nil, offset: CGPoint(x: 8, y: 0))
    }
    
    
    /// 懒加载
    // imageView
    private var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "tableview_loading")
        imageView.sizeToFit()
        return imageView
    }()
    
    // label
    private lazy var label: UILabel = {
        let label = UILabel()
        label.text = "开始刷新数据"
        label.sizeToFit()
        return label
    }()
}

// MARK: -
// TODO: 下拉刷新的  View
class ABPullDownRefreshView: UIView {
    // MARK: - 构造方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.whiteColor()
        
        prepareUI()
    }
    
    /// 准备UI
    private func prepareUI(){
        // 添加子控件
        addSubview(imageView)
        addSubview(label)
        
        // 添加约束
        imageView.ff_AlignInner(ff_AlignType.CenterLeft, referView: self, size: nil)
        label.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: imageView, size: nil, offset: CGPoint(x: 8, y: 0))
    }

    /// 懒加载
    // imageView
    private var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "tableview_pull_refresh")
        imageView.sizeToFit()
        return imageView
    }()
    
    // label
    private lazy var label: UILabel = {
        let label = UILabel()
        label.text = "下拉刷新数据"
        label.sizeToFit()
        return label
    }()
    
}